<template>
  <div class="review-container">
    <el-card>
      <div slot="header" class="header">
        <h3>奖学金评审与排名公示</h3>
        <div class="header-actions">
          <el-button type="primary" size="small" @click="generateRanking" :loading="generatingRanking">
            <i class="el-icon-refresh-right"></i> 生成排名
          </el-button>
          <el-button type="success" size="small" @click="exportToExcel" :loading="exporting">
            <i class="el-icon-download"></i> 导出Excel
          </el-button>
        </div>
      </div>
      
      <!-- 筛选条件 -->
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="学年">
          <el-select v-model="queryParams.year" placeholder="选择学年" clearable>
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="`${year}年`"
              :value="year">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学期">
          <el-select v-model="queryParams.semester" placeholder="选择学期" clearable>
            <el-option label="春季" value="春季"></el-option>
            <el-option label="秋季" value="秋季"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学院">
          <el-select v-model="queryParams.college" placeholder="选择学院" clearable @change="handleCollegeChange">
            <el-option
              v-for="college in collegeOptions"
              :key="college"
              :label="college"
              :value="college">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select v-model="queryParams.major" placeholder="选择专业" clearable @change="handleMajorChange" :disabled="!queryParams.college">
            <el-option
              v-for="major in majorOptions"
              :key="major"
              :label="major"
              :value="major">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级">
          <el-select v-model="queryParams.grade" placeholder="选择年级" clearable :disabled="!queryParams.major">
            <el-option
              v-for="grade in gradeOptions"
              :key="grade"
              :label="grade"
              :value="grade">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="queryParams.keyword" placeholder="学号/姓名" clearable>
            <el-button slot="append" icon="el-icon-search" @click="handleQuery"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 排名表格 -->
      <el-table
        :data="rankingList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{'background-color': '#f5f7fa', 'color': '#606266'}">
        <el-table-column prop="rank" label="排名" width="80" align="center"></el-table-column>
        <el-table-column prop="student_no" label="学号" width="120" align="center"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
        <el-table-column prop="college" label="学院" align="center"></el-table-column>
        <el-table-column prop="major" label="专业" align="center"></el-table-column>
        <el-table-column prop="grade" label="年级" width="100" align="center"></el-table-column>
        <el-table-column prop="class_name" label="班级" width="120" align="center"></el-table-column>
        <el-table-column label="思政表现得分" width="120" align="center">
          <template slot-scope="scope">
            <el-tag type="primary" size="medium">{{ scope.row.political_score || '0' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="科研能力得分" width="120" align="center">
          <template slot-scope="scope">
            <el-tag type="success" size="medium">{{ scope.row.research_score || '0' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="总分" width="100" align="center">
          <template slot-scope="scope">
            <el-tag type="danger" size="medium">{{ scope.row.total_score || '0' }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空数据提示 -->
      <div v-if="rankingList.length === 0 && !loading" class="empty-block">
        <el-empty description="暂无排名数据"></el-empty>
      </div>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Review',
  data() {
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        year: null,
        semester: null,
        college: '',
        major: '',
        grade: ''
      },
      // 年份选项
      yearOptions: [],
      // 学院选项
      collegeOptions: [],
      // 专业选项
      majorOptions: [],
      // 年级选项
      gradeOptions: [],
      // 排名列表
      rankingList: [],
      // 总记录数
      total: 0,
      // 加载状态
      loading: false,
      // 生成排名状态
      generatingRanking: false,
      // 导出状态
      exporting: false
    }
  },
  created() {
    this.initYearOptions()
    this.getCollegeOptions()
    this.getCurrentTerm()
  },
  methods: {
    // 初始化年份选项
    initYearOptions() {
      const currentYear = new Date().getFullYear()
      this.yearOptions = []
      for (let i = 0; i < 5; i++) {
        this.yearOptions.push(currentYear - i)
      }
    },
    
    // 获取当前学期
    getCurrentTerm() {
      const currentYear = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      this.queryParams.year = currentYear
      this.queryParams.semester = currentMonth >= 2 && currentMonth <= 7 ? '春季' : '秋季'
      this.getRankingList()
    },
    
    // 获取学院选项
    getCollegeOptions() {
      request.get('/ranking/colleges').then(res => {
        if (res.code === 200) {
          this.collegeOptions = res.data || []
        }
      }).catch(err => {
        console.error('获取学院列表失败:', err)
        this.$message.error('获取学院列表失败')
      })
    },
    
    // 处理学院变化
    handleCollegeChange() {
      this.queryParams.major = ''
      this.queryParams.grade = ''
      this.majorOptions = []
      this.gradeOptions = []
      
      if (this.queryParams.college) {
        request.get('/ranking/majors', {
          params: { college: this.queryParams.college }
        }).then(res => {
          if (res.code === 200) {
            this.majorOptions = res.data || []
          }
        }).catch(err => {
          console.error('获取专业列表失败:', err)
          this.$message.error('获取专业列表失败')
        })
      }
    },
    
    // 处理专业变化
    handleMajorChange() {
      this.queryParams.grade = ''
      this.gradeOptions = []
      
      if (this.queryParams.major) {
        request.get('/ranking/grades', {
          params: { major: this.queryParams.major }
        }).then(res => {
          if (res.code === 200) {
            this.gradeOptions = res.data || []
          }
        }).catch(err => {
          console.error('获取年级列表失败:', err)
          this.$message.error('获取年级列表失败')
        })
      }
    },
    
    // 获取排名列表
    getRankingList() {
      this.loading = true
      request.get('/ranking/list', {
        params: {
          college: this.queryParams.college,
          major: this.queryParams.major,
          grade: this.queryParams.grade,
          keyword: this.queryParams.keyword,
          year: this.queryParams.year,
          semester: this.queryParams.semester
        }
      }).then(res => {
        this.loading = false
        if (res.code === 200) {
          this.rankingList = res.data || []
          this.total = this.rankingList.length
        } else {
          this.$message.error(res.msg || '获取排名列表失败')
        }
      }).catch(err => {
        this.loading = false
        console.error('获取排名列表失败:', err)
        this.$message.error('获取排名列表失败，请稍后重试')
      })
    },
    
    // 生成排名
    generateRanking() {
      this.$confirm('确定要重新生成排名吗？这将覆盖当前学期的排名数据。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.generatingRanking = true
        request.post('/ranking/generate', {
          year: this.queryParams.year,
          semester: this.queryParams.semester
        }).then(res => {
          this.generatingRanking = false
          if (res.code === 200) {
            this.$message.success('排名生成成功')
            this.getRankingList()
          } else {
            this.$message.error(res.msg || '排名生成失败')
          }
        }).catch(err => {
          this.generatingRanking = false
          console.error('排名生成失败:', err)
          this.$message.error('排名生成失败，请稍后重试')
        })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 导出Excel
    exportToExcel() {
      this.exporting = true
      
      this.$message.info('开始导出，请稍候...')
      
      // 构建查询参数
      const params = {
        college: this.queryParams.college || '',
        major: this.queryParams.major || '',
        grade: this.queryParams.grade || '',
        keyword: this.queryParams.keyword || '',
        year: this.queryParams.year || '',
        semester: this.queryParams.semester || ''
      }
      
      // 获取token
      const token = window.sessionStorage.getItem('token')
      
      // 使用axios直接下载
      const baseUrl = process.env.VUE_APP_BASE_API || 'http://localhost:8082/api'
      
      // 创建一个a标签用于下载
      const link = document.createElement('a')
      link.style.display = 'none'
      document.body.appendChild(link)
      
      // 设置超时处理器
      let timeoutId = setTimeout(() => {
        this.$message.error('导出请求超时，请稍后重试')
        document.body.removeChild(link)
        this.exporting = false
        // 尝试中止请求
        if (xhr && xhr.abort) {
          xhr.abort()
        }
      }, 30000) // 30秒超时
      
      // 使用原生XMLHttpRequest处理二进制响应
      const xhr = new XMLHttpRequest()
      
      // 构建查询字符串
      const queryString = new URLSearchParams(params).toString()
      
      // 使用GET方法
      xhr.open('GET', `${baseUrl}/ranking/export?${queryString}`, true)
      xhr.responseType = 'blob'
      xhr.setRequestHeader('Authorization', `Bearer ${token}`)
      
      // 设置加载完成的回调
      xhr.onload = () => {
        // 清除超时处理器
        clearTimeout(timeoutId)
        
        if (xhr.status === 200) {
          // 检查内容类型
          const contentType = xhr.getResponseHeader('Content-Type')
          if (contentType && contentType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')) {
            // 正确的Excel类型
            const blob = new Blob([xhr.response], { 
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
            })
            const url = window.URL.createObjectURL(blob)
            link.href = url
            link.download = `学生综合排名_${this.queryParams.year}_${this.queryParams.semester}.xlsx`
            link.click()
            window.URL.revokeObjectURL(url)
            this.$message.success('导出成功')
          } else {
            // 可能是错误响应，尝试解析
            try {
              const reader = new FileReader()
              reader.onload = () => {
                try {
                  const errorData = JSON.parse(reader.result)
                  this.$message.error(errorData.msg || '导出失败')
                } catch (e) {
                  this.$message.error('导出失败，响应格式不正确')
                  console.error('导出错误，无法解析响应:', reader.result)
                }
              }
              reader.onerror = () => {
                this.$message.error('导出失败，无法读取响应')
              }
              reader.readAsText(xhr.response)
            } catch (e) {
              this.$message.error('导出失败，响应处理异常')
              console.error('导出响应处理异常:', e)
            }
          }
        } else {
          // 服务器错误状态码
          this.$message.error(`导出失败，服务器返回状态码 ${xhr.status}`)
          // 尝试解析错误响应
          try {
            const reader = new FileReader()
            reader.onload = () => {
              try {
                const errorData = JSON.parse(reader.result)
                console.error('服务器错误详情:', errorData)
              } catch (e) {
                console.error('无法解析服务器错误响应')
              }
            }
            reader.readAsText(xhr.response)
          } catch (e) {
            console.error('读取错误响应异常:', e)
          }
        }
        
        document.body.removeChild(link)
        this.exporting = false
      }
      
      // 设置错误处理回调
      xhr.onerror = (e) => {
        // 清除超时处理器
        clearTimeout(timeoutId)
        
        console.error('导出网络错误:', e)
        this.$message.error('网络错误，导出失败')
        document.body.removeChild(link)
        this.exporting = false
      }
      
      // 添加进度处理
      xhr.onprogress = (e) => {
        if (e.lengthComputable) {
          const percentComplete = Math.round((e.loaded / e.total) * 100)
          console.log(`下载进度: ${percentComplete}%`)
        }
      }
      
      // 发送请求
      xhr.send()
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getRankingList()
    },
    
    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: '',
        year: new Date().getFullYear(),
        semester: new Date().getMonth() + 1 >= 2 && new Date().getMonth() + 1 <= 7 ? '春季' : '秋季',
        college: '',
        major: '',
        grade: ''
      }
      this.majorOptions = []
      this.gradeOptions = []
      this.getRankingList()
    },
    
    // 处理分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getRankingList()
    },
    
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getRankingList()
    }
  }
}
</script>

<style scoped>
.review-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-form {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.empty-block {
  margin: 30px 0;
}
</style> 